﻿@using System.Collections
@using CoralNode.Core.Entity.Domains.Block
@using CoralNode.Core.Entity.Enums
@using Coralcode.Base.Entity
@using Coralcode.Base.Utils
@using Coralcode.Utils.Basic
@using CoralNode.MvcClient.Models.Block
@using Newtonsoft.Json
@model CoralNode.Core.Entity.Domains.Block.BlockDomain
@{
    Layout = null;
}
<style>
    .table_form td .fun {
        position: relative;
        top: 0;
        left: 0;
        right: 0;
        float: none;
    }
</style>
<script src="/Themes/CoralAdmin/_misc/scripts/ueditor/ueditor.all.js"> </script>
<script src="/Themes/CoralAdmin/_misc/scripts/ueditor/ueditor.config.js"> </script>
<form id="spform" action="/m/node/SaveBlock" method="post" enctype="multipart/form-data"
      class="js_validate">
    @if (@ViewBag.Msg != null) {
        <div class="error_msg">
            @ViewBag.Msg.Msg
        </div>
    }
    @if (Model.Type == SiteEnums.BlcokType.StaticNodeList) {
        <div class="content_tab extra_normal">
            <div class="tablist extra_normal" data-js="tab">
                <a href="#">内容列表</a>
                <a href="#">内容设置</a>
            </div>
        </div>
    }
    <div class="pt_3 js_tabcnt pr_2">
        @if (Model.Type == SiteEnums.BlcokType.StaticNodeList) {
            IList<BlockNodeView> blockNodeList = ViewBag.BlockNodeList;
            var nodeIds = blockNodeList.Select(n => n.NodeId).ToArray();
            string nodeValues = StringUtil.BuildCvs(nodeIds);
            var staticModel = !string.IsNullOrWhiteSpace(Model.Content)?JsonConvert.DeserializeObject<StaticNodeModel>(Model.Content):new StaticNodeModel();
            <div class="pl_2 pb_3 table_form form_main ">
                <div class="tablelist_style1" data-js="tabellist_style1">
                    <div class="funsearch p_1 pl_2 pr_2">
                        <a class="j_addNode btn_5 f_r ml_3" val="@nodeValues" href="/m/node/StaticNode?prototypeId=@staticModel.PrototypeId&categoryId=@staticModel.CategoryId">添加内容</a>
                        <select class="j_status_filter" style="float: right" href="/m/node/BlockDetail/@Model.Id?status=">
                            <option>状态筛选</option>
                            @foreach (var item in ViewBag.StaticNodeStatus) {
                                <option @(item.Value.ToString() == Request.QueryString["status"] ? "selected=selected" : string.Empty) value="@item.Value">@item.Key</option>
                            }
                        </select>
                    </div>
                    <style>
                        .tablelist_style1 tr {
                            cursor: move;
                        }
                    </style>
                    <table cellpadding="0" cellspacing="0" class="mt_3-5 j_table">
                        <tbody class="j_sortable">
                            <tr class="exclude">
                                <th width="100">ID</th>
                                <th style="text-align: left;">标题</th>
                                <th width="60">状态</th>
                                <th width="140">操作</th>
                            </tr>
                            @foreach (BlockNodeView item in blockNodeList) {
                                var node = item.ToNode();
                                <tr>
                                    <td class="j_itemId">@node.Id</td>
                                    <td>
                                        @Html.TextBox("NODETITLE", item.Title, new { @class = "text w_20" })
                                    <input type="hidden" name="blockNodes" value='{"BlockNodeId":"@item.Id","NodeId":"@node.Id","Status":"@item.BStatus","Title":"@Uri.EscapeDataString(item.Title)"}' />
                                </td>
                                <td class="j_status">
                                    <select>
                                        @foreach (var s in ViewBag.StaticNodeStatus) {
                                            <option @(s.Value == item.BStatus ? "selected=selected" : string.Empty) value="@s.Value">@s.Key</option>
                                        }
                                    </select>
                                </td>
                                <td>
                                    <div class="fun">
                                        <a href="/m/node/deleteStaticNode/@item.Id" class="js_ajaxdel">删除</a>
                                    </div>
                                </td>
                            </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        } else if (Model.Type == SiteEnums.BlcokType.DynamicNodeList) {
            DynamicNodeModel dynamicModel = null;
            try {
                dynamicModel = JsonConvert.DeserializeObject<DynamicNodeModel>(Model.Content) ?? new DynamicNodeModel();
            }
            catch (Exception) {

                dynamicModel = new DynamicNodeModel();
            }
            <div class="table_form form_main ">
                <div class="pb_3">
                    <table>
                        <tbody>
                            <tr>
                                <th width="100"><span class="signmark">*</span>内容类型：</th>
                                <td>
                                    <div class="js_selectType">

                                        <label class=" mr_2">
                                            <input type="radio" name="type" class="mt_0-5" value="prototype" @(dynamicModel.PrototypeId > 0 ? "checked=checked" : string.Empty) />原型
                                        </label>
                                        <label class=" mr_2">
                                            <input type="radio" name="type" class="mt_0-5" value="category" @(dynamicModel.CategoryId > 0 ? "checked=checked" : string.Empty) />分类
                                        </label>
                                        <label class=" mr_2">
                                            <input type="radio" name="type" class="mt_0-5" value="prototype,tag" @(dynamicModel.TagId > 0 ? "checked=checked" : string.Empty) />标签
                                        </label>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <th width="100" rowspan="2"><span class="signmark">*</span>排序方式：</th>
                                <td>
                                    <div class="js_order">
                                        <label class="mr_4 w_10">
                                            @{
            var byrank = dynamicModel.Orders == null ? null : dynamicModel.Orders.Where(n => n.Name.Equals("ByRank", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                                            }
                                            <input type="checkbox" value="ByRank" class="mt_0-5" @(byrank == null ? string.Empty : "checked=checked") />排序编号
                                        </label><label class="mr_2">
                                            <input type="radio" name="ByRank.dir" class="mt_0-5" value="Asc" @(byrank != null && string.Compare(byrank.Direction, "asc", true) == 0 ? "checked=checked" : string.Empty) />升序
                                        </label>
                                        <label>
                                            <input type="radio" name="ByRank.dir" class="mt_0-5" value="Desc" @(byrank != null && string.Compare(byrank.Direction, "Desc", true) == 0 ? "checked=checked" : string.Empty) />降序
                                        </label>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="js_order">
                                        <label class="mr_4 w_10">
                                            @{
            var bytime = dynamicModel.Orders == null ? null : dynamicModel.Orders.Where(n => n.Name.Equals("ByCreateTime", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                                            }
                                            <input type="checkbox" value="ByCreateTime" class="mt_0-5" @(bytime == null ? string.Empty : "checked=checked") />添加时间
                                        </label><label class="mr_2">
                                            <input type="radio" name="ByCreateTime.dir" class="mt_0-5" value="Asc" @(bytime != null && string.Compare(bytime.Direction, "asc", true) == 0 ? "checked=checked" : string.Empty) />升序
                                        </label>
                                        <label>
                                            <input type="radio" name="ByCreateTime.dir" class="mt_0-5" value="Desc" @(bytime != null && string.Compare(bytime.Direction, "Desc", true) == 0 ? "checked=checked" : string.Empty) />降序
                                        </label>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <th width="100"><span class="signmark">*</span>条数：</th>
                                <td>
                                    <input type="text" class=" text w_20" value="@(dynamicModel.Size == 0 ? 10 : dynamicModel.Size)" name="Size" />
                                </td>
                            </tr>
                            <tr data-type="prototype">
                                <th width="60"><span class="signmark">*</span>原型：</th>
                                <td>
                                    <div class="select_owner w_12 mr_1" data-meta="{value:'@dynamicModel.PrototypeId',name:'PrototypeId',fun:'getTag', btn:'
                                        <span class=\'ico ico_slide_down\'></span>' , clickbtn:'<span class=\'ico ico_slide_up\'></span>'}">
                                        <ul>
                                            @*<li data-value="0">全部</li>*@
                                            @foreach (var item in @ViewBag.PrototypeList) {
                                                <li data-value="@item.Id">@item.Title</li>
                                            }
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <tr data-type="category">
                                <th>分类：</th>
                                <td>
                                    <div class="ztreeContainer">
                                        <input type="text" class="text w_12 required js_ztree_trigger" id="category_title"
                                               value="" />
                                        <input type="hidden" name="CategoryId" id="parent_id" value="@dynamicModel.CategoryId" />
                                        <span><a id="menuBtn" href="#" class="js_ztree_trigger">选择</a></span>
                                        <ul id="parent_list" class="ztree" style="margin-top: 0; width: 180px;"></ul>
                                        <textarea class="js_ztree_data" style="display: none;">@ViewBag.ZtreeCategory</textarea>
                                    </div>
                                </td>
                            </tr>
                            <tr data-type="tag">
                                <th>标签：</th>
                                <td>
                                    <div class="select_owner w_12 mr_1 js_tagList" data-meta="{value:'@dynamicModel.TagId',name:'TagId', btn:'
                                        <span class=\'ico ico_slide_down\'></span>' , clickbtn:'<span class=\'ico ico_slide_up\'></span>'}">
                                        <ul>
                                            @*<li data-value="0">全部</li>*@
                                            @if (ViewBag.TagList != null) {
                                                foreach (var item in @ViewBag.TagList) {
                                                    <li data-value="@item.Id">@item.Title</li>
                                                }
                                            }
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    @Html.Hidden("Content", Model.Content, new { @class = "js_dynamicNodeContent" })
                </div>
            </div>
        }
        <div class="table_form form_main ">
            <div class="">
                <table>
                    <tbody class="menuType">
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)
                        <tr>
                            <th width="100"><span class="signmark">*</span>标题</th>
                            <td>
                                <input type="text" name="Title" class="text w_37 required" value="@Model.Title" />
                                <input type="hidden" name="Id" value="@Model.Id" />
                            </td>
                        </tr>
                        <tr>
                            <th>是否缓存</th>
                            <td>
                                <label class=" mr_2">
                                    <input type="radio" name="IsCache" class="mt_0-5" value="@DomainEnums.Binary.True" @(Model.IsCache == DomainEnums.Binary.True ? "checked=checked" : string.Empty) />是
                                </label>
                                <label class=" mr_2">
                                    <input type="radio" name="IsCache" class="mt_0-5" value="@DomainEnums.Binary.False" @(Model.IsCache == DomainEnums.Binary.False ? "checked=checked" : string.Empty) />否
                                </label>
                            </td>
                        </tr>
                        @if (Model.Type == SiteEnums.BlcokType.FreeNode) {
                            <tr>
                                <th>具体内容</th>
                                <td>
                                    <textarea id="content" name="content">@Model.Content</textarea>
                                    <script type="text/javascript">
                                        UE.getEditor("content")
                                    </script>
                                </td>
                            </tr>
                        } else if (Model.Type == SiteEnums.BlcokType.Url) {
                            <tr>
                                <th>链接</th>
                                <td>
                                    @Html.TextBoxFor(m => m.Content, new { @class = "text w_37" })
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="submitbox p_2 extra_normal">
        <input type="submit" class="btn_1" value="提    交" />
    </div>
</form>
<script>
    function getChooseValue() {
        var chooseValue = '';
        var chooseArray = new Array();
        $('.j_table tr:not(.exclude)').each(function (i, n) {
            chooseArray.push($(n).find('.j_itemId').text());
        });
        chooseValue = chooseArray.join(',');
        return chooseValue;
    }
    function getTag($obj) {
        var value = $obj.find("input[type='hidden']").val();
        var $tagUl = $(".js_tagList ul");
        if ($tagUl.parents("tr").is(":hidden")) {
            return false;
        }
        $.post("/m/node/GetTagList/" + value, function (data) {
            if (data != undefined && data != null && data.length > 0) {
                $tagUl.empty();
                for (var i = 0; i < data.length; i++) {
                    $tagUl.append("<li data-value='" + data[i].Id + "'>" + data[i].Title + "</li>");
                }
                $(".js_tagList").dropdown_owner().css("zIndex", 10);
            }
        });
    };

    $(document).ready(function () {
        var js = $('[data-js]');
        js.filter('[data-js="tab"]').tabs(".js_tabcnt > div");
        $('.j_sortable').sortable({
            axis: "y", cancel: "tr.exclude,input,.j_status", stop: function (event, ui) {
                if (ui.item.next().hasClass("exclude")) {
                    var trExlude = ui.item.next();
                    trExlude.after(ui.item);
                }
            }
        });
        $('.j_addNode').click(function (e) {
            var $this = $(this);
            e.preventDefault();
            var uploadDialog = $.dialog({
                title: '',
                content: '<img src="/Themes/CoralAdmin/_misc/images/loading.gif" style="display:block; margin:30px auto;" />',
                background: "#000",
                opacity: 0.4,
                lock: true,
                padding: "0"
            });
            $(".tablelist_style1").trigger("colorcross");



            uploadDialog.getJQuery().data("params", { okfun: savefun });
            $.post($this.attr("href"), { value: $this.attr("val") }, function (data) {
                uploadDialog.content(data);
            });

            function savefun(nodes) {
                var html = '';
                for (var i = 0; i < nodes.length; i++) {
                    html += '<tr><td class="j_itemId">' + nodes[i].Id + '</td><td><input type="text" name="NODETITLE" value="' + nodes[i].Title + '" class="text w_20" /><input type="hidden" name="blockNodes" value=\'{"BlockNodeId":"0","Status":"@NodeEnums.StaticNodeStatus.Audit","NodeId":"' + nodes[i].Id + '","Title":"' + encodeURIComponent(nodes[i].Title) + '"}\'/></td><td class="j_status"><select>@foreach (var s in ViewBag.StaticNodeStatus){<option @(s.Value==2?"selected=selected":string.Empty) value="@s.Value">@s.Key</option>}</select></td><td><div class="fun"><a href="/m/node/deleteNode/1" class="js_delete">删除</a></div></td></tr>';
                }
                $('.j_table').append(html);
                var chooseValue = getChooseValue();
                $this.attr('val', chooseValue);
                $(".tablelist_style1").trigger("colorcross");
                uploadDialog.close();
            }
        });

        $(".tablelist_style1 input[type='text']").live("blur", function (e) {
            e.preventDefault();
            e.stopPropagation();
            var $this = $(this);
            var value = encodeURIComponent($this.val());
            var modelJson = $.parseJSON($this.next().val());
            modelJson.Title = value;
            $this.next().val(JSON.stringify(modelJson));
        });
        $(".select_owner").dropdown_owner();

        $(".ztreeContainer").each(function () {
            var $this = $(this),
                $text = $this.find("input[type='text']"),
                $hidden = $this.find("input[type='hidden']"),
                data = $this.find(".js_ztree_data").val(),
                $ztree = $this.find(".ztree");
            $this.find(".js_ztree_data").hide();
            $ztree.zTreeInit({
                trigger: $this.find(".js_ztree_trigger"),
                checkFun: function(treeNode) {
                    var showText = treeNode.name;
                    var tempNode = treeNode;
                    while (tempNode.getParentNode() != null) {
                        tempNode = tempNode.getParentNode();
                        showText = tempNode.name + " > " + showText;
                    }

                    $text.val(showText);

                    $hidden.val(treeNode.id);
                },
                data: data
            });
        });

        var $jsSelectType = $(".js_selectType");
        var trs = $jsSelectType.parents("table").first().find("tr[data-type]");
        trs.hide();
        $jsSelectType.find("input[name='type']").click(function (e) {
            var $this = $(this),
                values = $this.val().split(',');
            trs.hide();
            for (var i = 0; i < values.length; i++) {
                trs.filter("[data-type='" + values[i] + "']").show();
            }
        });
        var checkedItem = $jsSelectType.find("input[name='type']:checked");
        if (checkedItem.length > 0)
            checkedItem.trigger("click");
        else {
            $jsSelectType.find("input[name='type']").first().trigger("click");
        }
        var $orderContainers = $(".js_order");

        var $orderCheck = $orderContainers.find("input[type='checkbox']");
        if ($orderCheck.filter(":checked").length == 0) {
            $orderCheck.attr("checked", "checked");
            $orderCheck.parent().each(function() {
                $(this).siblings().last().find("input[type='radio']").attr("checked", "checked");
            });
        }
        $('form').submit(function (e) {
            e.preventDefault();
            if (!$(this).valid()) {
                return false;
            }
            if ($(".js_dynamicNodeContent").length > 0) {
                var $inputs = $(".js_dynamicNodeContent").prev().find("input[type='text'],input[type='hidden']");
                $inputs.each(function () {
                    if ($(this).parents("tr").is(":hidden")) {
                        $(this).val("");
                    }
                })
                var tempStr = "{";
                tempStr += '"CategoryId":' + ($inputs.filter("[name='CategoryId']").val() == "" ? 0 : $inputs.filter("[name='CategoryId']").val()) + ",";
                tempStr += '"PrototypeId":' + ($inputs.filter("[name='PrototypeId']").val() == "" ? 0 : $inputs.filter("[name='PrototypeId']").val()) + ",";
                tempStr += '"TagId":' + ($inputs.filter("[name='TagId']").val() == "" ? 0 : $inputs.filter("[name='TagId']").val()) + ",";
                tempStr += '"Size":' + ($inputs.filter("[name='Size']").val() == "" ? 0 : $inputs.filter("[name='Size']").val()) + ",";
                tempStr += '"Orders":[';
                $orderContainers.each(function () {
                    var $this = $(this);
                    if ($this.find("input[type='checkbox']:checked").length > 0) {

                        tempStr += '{';
                        tempStr += '"Name":"' + $this.find("input[type='checkbox']").val() + '",';
                        tempStr += '"Direction":"' + $this.find("input[type='radio']:checked").val() + '"';
                        tempStr += '},';
                    }
                });
                tempStr = tempStr.trimEnd(',');
                tempStr += ']';
                tempStr += "}";
                $(".js_dynamicNodeContent").val(tempStr);
            }
            $.post($(this).attr("action"), $(this).serialize(), function (data) {
                $('.nav_left li.current a').trigger('click');
                $.alert(data.Msg);
                setTimeout("$('.d-close').trigger('click')", 1000);
            });
            return false;
        });
        $('.j_status select').change(function () {
            var $this = $(this);
            var $blockNodes = $this.parents('tr').find('input[name="blockNodes"]');
            var nodeBlock = JSON.parse($blockNodes.val());
            nodeBlock.Status = $this.val();
            $blockNodes.val(JSON.stringify(nodeBlock));
        });
    });
</script>
